<template>
	<view class="page">
		<u-navbar
			title="消息"
			@rightClick="rightClick"
			:autoBack="true"
			placeholder
		>
			<view class="navbar__right" slot="right">
				<view class="navbar__right--icon">
					<image src="@/static/theme/default/home/clear.png" mode=""></image>
				</view>
				<view class="navbar__right--text">清除未读</view>
			</view>
		</u-navbar>
		
		<view class="page__head">
			 <u-tabs
				:list="menu"
				:current="current"
				lineWidth="30"
				lineColor="#f56c6c"
				:activeStyle="{
					color: '#303133',
					fontWeight: 'bold',
					transform: 'scale(1.05)'
				}"
				:inactiveStyle="{
					color: '#606266',
					transform: 'scale(1)'
				}"
				itemStyle=" height: 34px;"
				@change="menuChange"
			>
			</u-tabs>
		</view>
		
		<view class="page__body" :list="list" :change:list="notice.listChange">
			<z-paging ref="paging" class="z-paging" :auto-show-back-to-top="true" :auto="false" v-model="list" @query="queryList">
				<view class="comment-card" v-for="item in list" :key="item.KeyId" @click="commentClick(item)">
					<view class="comment-card__left">
						<view class="comment-card__left--avator">
							<avator :avator="item.avator" :name="item.CreateUser"></avator>
						</view>
					</view>
					<view class="comment-card__right">
						<view class="comment-card__right--name" style="position: relative;">
							<view class="">
								<text class="" style="margin-right: 20rpx;font-size: 25rpx;color: #888888;" v-show="current != 3">{{item.CreateUser}}</text>
								<text style="position: relative;">
									<text style="font-size: 25rpx;color: #c6c6c6;">{{item.TitleDesc}}</text>
									<text class="" v-show="item.ReadState == '0'" style="background-color: red;width: 15rpx;height: 15rpx;border-radius: 50%;position: absolute;right: -25rpx;top: -3rpx;display: inline-block;"></text>
								</text>
							</view>
							
							<view class="comment-card__right--bottom">
								<view class="" style="color: #aaa;font-size: 25rpx;">{{item.CreateTime}}</view>
							</view>
						</view>
						<view class="comment-card__right--content">
							<view class="comment-card__right--content__replay" v-html="item.ReplyContent" v-show="current != 2"></view>
							<view class="comment-card__right--content__topic" v-html="item.TopicContent"></view>
						</view>
					</view>
				</view>
			</z-paging>
		</view>
		
		<comment-pop :show="userCommentVisible" :id="id" :data="userCommentData" @close="closeCommentPop"></comment-pop>
		<loading :loading="loading"/>
	</view>
</template>

<script>
	import _custom from '@/common/_custom.js'
	import _data from '@/common/_data.js'
	import moment from 'moment';
	import {timestampFormat,entitiestoUtf16} from '@/common/custom_util.js'
	import Avator from '@/components/custom/avator/avator.vue'
	import Loading from '@/components/custom/loading/loading.vue'
	import emoji_default from '@/static/js/message/emoji_data.js';
	import emoji_jxp from '@/static/js/jxp.js';
	
	export default {
		components: {
			Avator,Loading
		},
		data() {
			return {
				obsusername: _data.localData('name'),
				pxid: _data.localData('userid'),
				static_avator: _data.data('static_url'),
				emojiDic: emoji_default.emoji_dic,
				jxpDic: emoji_jxp.jxp_dic,
				component: null,
				componentVisible: false,
				menu: [
					{
						name: '回复我的',
						icon: require('@/static/theme/default/home/huifu.png'),
						badge: {
							isDot: false
						}
					},
					{
						name: '@我的',
						icon: require('@/static/theme/default/home/at.png'),
						badge: {
							isDot: false
						}
					},
					{
						name: '收到的赞',
						icon: require('@/static/theme/default/home/zhan.png'),
						badge: {
							isDot: false
						}
					},
					{
						name: '我的回复',
						icon: require('@/static/theme/default/home/huifu.png'),
					},
				],
				current: 0,
				list: [],
				currentpage: 1,
				pagesize: 10,
				unReadCount: {
					LikesUnReadCount: 0,
					ReplyUnReadCount: 0
				},//未读数
				userCommentVisible: false,
				userCommentData: {
					topicid: '',
					floorid: ''
				},
				id: '',
				isDataRender: false,
				isPageRender: false,
			}
		},
		onShow() {
			this.getTopicUnReadCount();
		},
		onReady() {
			this.getDataJava();
			this.isPageRender = true;
		},
		computed: {
			loading() {
				return this.isPageRender && this.isDataRender ? false : true;
			},
		},
		methods: {
			/**
			 * 获取主题回复相关未读数量
			 */
			getTopicUnReadCount() {
				let that = this;
				_custom.getDataJava({
					apiname: 'getTopicUnReadCount',
					apiparam: {
						obsusername: this.obsusername,
						obspxid: this.pxid
					},
					success(res) {
						if(res.length) that.unReadCount = res[0];
						that.setMenuStatus();
					}
				})
			},
			/**
			 * 设置未读状态
			 */
			setMenuStatus() {
				this.menu[2].badge.isDot = this.unReadCount.LikesUnReadCount == 0 ? false : true;
				this.menu[0].badge.isDot = this.unReadCount.ReplyUnReadCount == 0 ? false : true;
				this.menu[1].badge.isDot = this.unReadCount.AtUnReadCount == 0 ? false : true;
			},
			/**
			 * 根据回复Id清除未读状态
			 */
			setReplyReadStateById(v) {
				let that = this;
				_custom.getDataJava({
					apiname: 'setReplyReadStateById',
					code: 2,
					apiparam: {
						replyid: v
					},
				})
			},
			/**
			 * 根据艾特信息Id清除未读状态
			 */
			setAtReadStateById(v) {
				let that = this;
				_custom.getDataJava({
					apiname: 'setAtReadStateById',
					code: 2,
					apiparam: {
						atid: v
					},
				})
			},
			/**
			 * 清除当前人"回复我的"未读状态
			 */
			clearReplyReadState() {
				let that = this;
				_custom.getDataJava({
					apiname: 'clearReplyReadState',
					code: 2,
					apiparam: {
						obsusername: this.obsusername,
						obspxid: this.pxid
					},
				})
			},
			/**
			 * 清除当前人"@我的"未读状态
			 */
			clearAtReadState() {
				let that = this;
				_custom.getDataJava({
					apiname: 'clearAtReadState',
					code: 2,
					apiparam: {
						obsusername: this.obsusername,
						obspxid: this.pxid
					},
				})
			},
			/**
			 * 清除当前人"收到的赞"未读状态
			 */
			clearLikesReadState() {
				let that = this;
				_custom.getDataJava({
					apiname: 'clearLikesReadState',
					code: 2,
					apiparam: {
						obsusername: this.obsusername,
						obspxid: this.pxid
					},
				})
			},
			/**
			 * 调用接口
			 */
			getListData(v) {
				let that = this;
				_custom.getDataJava({
					apiname: v,
					pagesize: this.pagesize,
					currentpage: this.currentpage,
					apiparam: {
						obsusername: this.obsusername,
						obspxid: this.pxid
					},
					success(res) {
						if(that.$refs.paging) that.$refs.paging.complete(that.formatData(res));
						that.$nextTick(() => {
							setTimeout(() => {
								 that.isDataRender = true;
							},800);
						})
					}
				})
			},
			/**
			 * 格式化返回的数据
			 * @param {Object} v
			 */
			formatData(v) {
				v.forEach(item => {
					item.avator = this.static_avator + "/static/photo/user/" + item.CreatePxid + "/70.jpg";
					let topicContent = item.TopicContent;
					let lastReply = item.LastReply;
					let replyContent = item.ReplyContent;
					if(topicContent) {
						topicContent = entitiestoUtf16(item.TopicContent);
						topicContent = topicContent.replace(/%22/g,"\"");
						topicContent = this.replaceEmoji(topicContent);
					}
					if(lastReply) {
						lastReply = entitiestoUtf16(item.LastReply);
						lastReply = lastReply.replace(/%22/g,"\"");
						lastReply = this.replaceEmoji(lastReply);
					}
					if(replyContent) {
						replyContent = entitiestoUtf16(item.ReplyContent);
						replyContent = replyContent.replace(/%22/g,"\"");
						replyContent = this.replaceEmoji(replyContent);
					}
					switch(this.current) {
						case 0:
						case 1:
						case 3:
							item.TopicContent = item.LastReply ? lastReply : topicContent;
							break;
						case 2:
							if(item.Pid == '') {
								item.TopicContent = topicContent;
							} else {
								item.TopicContent = replyContent;
							}
							break;
					}
					item.ReplyContent = replyContent;
					item.CreateTime = timestampFormat(item.CreateTime);
				})
				return v
			},
			/**
			 * 获取当前选项下数据
			 */
			getDataJava() {
				switch(this.current) {
					case 0://回复我的
						this.getListData('getTopicMyReceiveList');
						break;
					case 1://@我的
						this.getListData('getTopicMyAtList');
						break;
					case 2://收到的赞
						this.getListData('getTopicMyLikesList');
						break;
					case 3://我的回复
						this.getListData('getTopicMyCreateList');
						break;
				}
			},
			/**
			 * 初始化分页参数
			 */
			initPage() {
				this.pagesize = 10;
				this.currentpage = 1;
				this.$refs.paging.reload();
			},
			/**
			 * 分页请求的方法(初始化会执行，相当于写在onload中)
			 * @param {Object} pageNo	当前页码
			 * @param {Object} pageSize		每页数量
			 */
			queryList(pageNo, pageSize) {
				this.pagesize = pageSize;
				this.currentpage = pageNo;
				this.getDataJava()
			},
			/**
			 * 切换菜单
			 * @param {Object} e
			 */
			menuChange(e) {
				this.current = e.index;
				this.initPage();
				if(this.current == '2') {
					this.unReadCount.LikesUnReadCount == 0;
					this.setMenuStatus();
					this.clearLikesReadState()
				}
			},
			/**
			 * 点击回复
			 * @param {Object} v
			 */
			commentClick(v) {
				console.log(v)
				switch(this.current) {
					case 0:
					case 1://艾特我的
					case 2:
						if(v.ReadState == '0' && this.current == 0) this.setReplyReadStateById(v.Id);
						if(v.ReadState == '0' && this.current == 1) this.setAtReadStateById(v.AtId);
						if(v.ReadState == '0' && this.current == 0) this.unReadCount.ReplyUnReadCount = this.unReadCount.ReplyUnReadCount*1 - 1;
						if(v.ReadState == '0' && this.current == 1) this.unReadCount.AtUnReadCount = this.unReadCount.AtUnReadCount*1 - 1;
						this.$set(v,'ReadState','1');
						if(v.TopicContent == '内容已被删除') {
							uni.showToast({
								title: v.TopicContent,
								icon: 'none'
							})
							return
						}
						break;
					case 3:
						if(v.TopicContent == '内容已被删除') return
						break;
				}
				this.setMenuStatus();
				if(v.Pid == '-1') {
					uni.navigateTo({
						url: v.TopicRouter + '?businessId=' + v.BusinessId + '&id=' + v.Id
					})
					return
				} else if(v.Pid == '') {
					uni.navigateTo({
						url: v.TopicRouter + '?businessId=' + v.BusinessId
					})
					return
				} 
				this.id = v.Id;
				this.userCommentData.topicid = v.TopicId;
				this.userCommentData.floorid = v.FloorId;
				this.userCommentVisible = true;
			},
			/**
			 * 关闭评论弹窗
			 */
			closeCommentPop() {
				this.initPage();
				this.userCommentVisible = false;
			},
			/**
			 * 清除未读
			 */
			rightClick() {
				let that = this;
				uni.showModal({
					title: '是否清除全部未读？',
					success(res) {
						if(res.confirm) {
							Promise.all([that.clearLikesReadState(),that.clearAtReadState(),that.clearReplyReadState()]).then(() => {
								that.getTopicUnReadCount()
								that.list.forEach(item => {
									item.ReadState = '1'
								})
								uni.showToast({
									title: '清除成功',
									icon: 'none'
								})
							})
						}
					}
				})
			},
			//替换表情符号为图片
			replaceEmoji(str) {
				let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g, (item, index) => {
					let key = item;
					let defaultValue = this.emojiDic[key] ? this.emojiDic[key].url : '';
					let jxpValue = this.jxpDic[key] ? this.jxpDic[key].url : '';
					let imgstr = '';
					if(defaultValue) {
						// #ifdef H5
						imgstr = '<img class="comment-default pic comment-emoji" style="width:22px;height:22px;" src="' + _data.data('static_url') + '/static/emoji/' + this.emojiDic[key].url + '">';
						// #endif
						// #ifdef APP-PLUS
						let url = plus.io.convertLocalFileSystemURL('_www/static/img/emoji/' + this.emojiDic[key].url);
						imgstr = '<img class="comment-default pic comment-emoji" style="width:22px;height:22px;" src="' + url + '">';
						// #endif
						return imgstr;
					} else if(jxpValue) {
						// #ifdef H5
						imgstr = '<img class="comment-jxp pic comment-emoji" style="width:100px;height:100px;" src="' + _data.data('static_url') + '/static/emoji/jxp/' + this.jxpDic[key].url + '.gif">';
						// #endif
						// #ifdef APP-PLUS
						let url = plus.io.convertLocalFileSystemURL('_www/static/img/jxp/gif/' + this.jxpDic[key].url + '.gif');
						imgstr = '<img class="comment-jxp pic comment-emoji" style="width:100px;height:100px;" src="' + url + '">';
						// #endif
					}
					return imgstr;
				});
				replacedStr = replacedStr.replace(/(\r\n)|(\n)/g, '<br/>');
				return replacedStr;
			},
		}
	}
</script>

<script module="notice" lang="renderjs">
	import {
		js_image_cache,formatImg
	} from '@/common/custom_util.js';
	import _data from '@/common/_data.js'
	
	export default {
		data() {
			return {
	
			}
		},
		mounted() {
			
		},
		methods: {
			listChange(newVal,oldVal,ownerInstance) {
				let el = document.getElementsByClassName("img")
				let box = document.getElementsByClassName("comment-card__right--content")[0];
				let els = document.getElementsByClassName("pic");
				// // #ifdef APP-PLUS
				// if(els.length) {
				// 	for (let i = 0; i < els.length; i++) {
				// 		let item = els[i];
				// 		if(item.dataset.key) {
				// 			let index = item.dataset.key.indexOf('homepage');
				// 			let name = item.dataset.key.substring(index);
				// 			let extensionIndex = item.dataset.key.lastIndexOf('.');
				// 			let extension = item.dataset.key.substring(extensionIndex);
				// 			if(extension == '.gif') {
				// 				let src = item.dataset.key.replace('_minPic','');
				// 				js_image_cache(src,name,res => {
				// 					item.src = res;
				// 				})
				// 			} else {
				// 				js_image_cache(item.dataset.key,name,res => {
				// 					item.src = res;
				// 				})
				// 			}
				// 			item.dataset.key = '';
				// 		}
				// 	}
				// }
				// // #endif
				// // #ifdef H5
				// for (let i = 0; i < els.length; i++) {
				// 	let item = els[i];
				// 	if(item.dataset.key) {
				// 		let index = item.dataset.key.lastIndexOf('.');
				// 		let extension = item.dataset.key.substring(index);
				// 		if(extension == '.gif') {
				// 			let src = item.dataset.key.replace('_minPic','');
				// 			item.src = src;
				// 			continue
				// 		}
				// 		item.src = item.dataset.key;
				// 	}
				// }
				// // #endif
				if(el.length) {
					for (let i = 0; i < el.length; i++) {
						let item = el[i];
						item.src = formatImg(item.dataset.key,false);
						item.onload = function() {
							item.setAttribute('style', 'opacity: 1;');
						}
						item.onerror = function(e) {
							let url = '';
							// #ifdef APP-PLUS
							url = plus.io.convertLocalFileSystemURL('_www/static/img/load_err.png');
							// #endif
							// #ifdef H5
							url = '/static/img/load_err.png';
							// #endif
							this.onerror = null;
							this.src = url;
						}
						let w = '';
						let h = '';
						if(box.clientWidth < item.width) {
							w = box.clientWidth;
							h = item.height / item.width * box.clientWidth;
						} else {
							w = item.width;
							h = item.height;
						}
						if(item.width / 4 > 50) {
							w = item.width / 4;
							h = item.height / 4;
						}
						item.width = w;
						item.height = h;
					}
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.page {
		height: 100vh;
		
		&__head {
			position: fixed;
			top: calc(var(--status-bar-height) + 44px);
			/* #ifdef H5 */
			top: 88rpx;
			/* #endif */
			left: 0;
			z-index: 9;
			width: 100%;
			height: 50px;
			background-color: #fff;
			border-bottom: 1rpx solid #eee;
		}
		
		&__body {
			background-color: #fff;
			height: calc(100vh);
		}
	}
	
	.page__head /deep/ .u-tabs__wrapper__nav__item {
		flex: 1;
		padding: 0;
	}
	
	.comment-card {
		display: flex;
		padding-top: 20rpx;
		position: relative;
		max-width: 100%;
		overflow: hidden;
		
		&__set {
			position: absolute;
			right: 40rpx;
			top: 20rpx;
			width: 30rpx;
			height: 30rpx;
			
			image {
				width: 100%;
				height: 100%;
			}
		}
		
		&__left {
			width: 100rpx;
			
			&--avator {
				width: 70rpx;
				height: 70rpx;
				margin: 0 20rpx;
			}
		}
		
		&__right {
			width: calc(100% - 120rpx);
			border-bottom: 1rpx solid #eee;
			padding-bottom: 20rpx;
			margin-right: 20rpx;
			
			&--name {
				color: #333;
				display: flex;
				justify-content: space-between;
				align-items: center;
				
				&-more {
					width: 30rpx;
					height: 30rpx;
					
					image {
						width: 100%;
						height: 100%;
					}
				}
			}
			
			&--time {
				font-size: 25rpx;
				color: #aaa;
				margin-bottom: 20rpx;
			}
			
			&--content {
				padding: 20rpx 0;
				max-width: 100%;
				overflow: hidden;
				
				&__replay {
					margin-bottom: 20rpx;
					max-width: 100%;
					overflow: hidden;
					color: #1f1f1f;
					font-size: 33rpx;
					max-height: 400rpx;
				}
				
				&__topic {
					background-color: #fafafa;
					border-radius: 5rpx;
					max-width: 100%;
					overflow: hidden;
					padding: 20rpx;
					box-sizing: border-box;
					color: #595959;
					font-size: 30rpx;
				}
			}
		}
	}
	
	.z-paging {
		margin-top: calc(var(--status-bar-height) + 94px);
	}
	
	.comment-card__right--content /deep/ .comment-jxp {
		width: 100rpx !important;
		height: 100rpx !important;
	}
	
	.comment-card__right--content /deep/ .img {
		border-radius: 10rpx;
		margin-right: 10rpx;
		opacity: 0;
	}
	
	.navbar__right {
		display: flex;
		
		&--icon {
			width: 40rpx;
			height: 40rpx;
			margin-right: 10rpx;
			
			image {
				width: 100%;
				height: 100%;
			}
		}
		
		&--text {
			font-size: 25rpx;
			color: #8a8a8a;
		}
	}
</style>
